package com.gqj.meter.service.impl;

import com.gqj.common.constant.BusinessConstants;
import com.gqj.common.exception.ServiceException;
import com.gqj.common.utils.DateUtils;
import com.gqj.common.utils.StorageUtil;
import com.gqj.common.utils.StringUtils;
import com.gqj.common.utils.bean.BeanValidators;
import com.gqj.common.utils.uuid.HiultraUtil;
import com.gqj.meter.controller.MdInTaskDetailsController;
import com.gqj.meter.domain.*;
import com.gqj.meter.mapper.*;
import com.gqj.meter.service.IMdInTaskDetailsService;
import com.gqj.soapclient.client;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.xml.sax.SAXException;

import javax.validation.Validator;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 出入库明细Service业务层处理
 *
 * @author lxq
 * @date lxq-02-10
 */
@Service
public class MdInTaskDetailsServiceImpl implements IMdInTaskDetailsService {
    @Autowired
    private MdInTaskDetailsMapper mdInTaskDetailsMapper;
    @Autowired
    private MdInTaskMapper mdInTaskMapper;
    @Autowired
    private MdMeterMapper mdMeterMapper;
    @Autowired
    private MdItMapper mdItMapper;
    @Autowired
    private MdLcEquipMapper mdLcEquipMapper;
    @Autowired
    private MdConcentratorMapper mdConcentratorMapper;
    @Autowired
    private MdComModuleMapper mdComModuleMapper;
    @Autowired
    private MdOtherMaterialMapper mdOtherMaterialMapper;
    @Autowired
    private MdOutTaskDetailsMapper mdOutTaskDetailsMapper;
    @Autowired
    private MdChkTaskDetailsMapper mdChkTaskDetailsMapper;
    @Autowired
    protected Validator validator;
    private static final Logger log = LoggerFactory.getLogger(MdInTaskDetailsServiceImpl.class);

    //    @Autowired
//    private MdIoDetMapper mdIoDetMapper;
    @Autowired
    private TransactionTemplate transactionTemplate;

    /**
     * 查询出入库明细
     *
     * @param inTaskDetailsId 出入库明细主键
     * @return 出入库明细
     */
    @Override
    public MdInTaskDetails selectMdInTaskDetailsByInTaskDetailsId(Long inTaskDetailsId) {
        return mdInTaskDetailsMapper.selectMdInTaskDetailsByInTaskDetailsId(inTaskDetailsId);
    }

    /**
     * 查询出入库明细列表
     *
     * @param mdInTaskDetails 出入库明细
     * @return 出入库明细
     */
    @Override
    public List<MdInTaskDetails> selectMdInTaskDetailsList(MdInTaskDetails mdInTaskDetails) {
        return mdInTaskDetailsMapper.selectMdInTaskDetailsList(mdInTaskDetails);
    }

    /**
     * 查询出入库明细列表
     *
     * @param mdInTaskDetails 出入库明细
     * @return 出入库明细
     */
    @Override
    public List<MdInTaskDetails> exportMdInTaskDetailsListExcel(MdInTaskDetails mdInTaskDetails) {
        return mdInTaskDetailsMapper.exportMdInTaskDetailsListExcel(mdInTaskDetails);
    }

    /**
     * 新增入库明细
     *
     * @param mdInTaskDetailsList 入库明细
     * @return 结果
     */
    @Override
    @Transactional
    public int insertMdInTaskDetails(List<MdInTaskDetails> mdInTaskDetailsList) {
        MdInTaskDetails mdInTaskDetailsMain = mdInTaskDetailsList.get(0);
        MdInTask mdInTask = mdInTaskMapper.selectMdInTaskByInTaskNo(mdInTaskDetailsMain.getInTaskNo());
//        if (!"0".equals(mdInTask.getStatusCode())) {
//            throw new ServiceException("任务不是待执行状态，不允许新增明细！");
//        }

        for (MdInTaskDetails mdInTaskDetails : mdInTaskDetailsList) {
            //如果单据为拆回设备，需要判断是否存在物资信息，不存在则新增
            if (mdInTask.getTaskOrderType().equals(BusinessConstants.TASK_ORDER_TYPE_RETURN)) {

                //根据设别码获取对应实体
                String assetsCategorySelect = StorageUtil.getEquipCodeType(mdInTaskDetails.getEquipCode());

                if (BusinessConstants.ASSETS_CATEGORY_METER.equals(assetsCategorySelect)) {

                    MdMeter mdMeterTemp = mdMeterMapper.selectMdMeterByRfidNo(mdInTaskDetails.getRfidNo());
                    MdMeter meter = new MdMeter();
                    if (StringUtils.isNull(mdMeterTemp)) {
                        if (mdInTask.getTaskOrderType().equals(BusinessConstants.TASK_ORDER_TYPE_RETURN)) {
                            meter.setRfidNo(mdInTaskDetails.getRfidNo());
                            meter.setCurStatusCode(BusinessConstants.CUR_STATUS_CODE_RETURN);
                            meter.setEquipCode(mdInTaskDetails.getEquipCode());
                            meter.setEquipName(mdInTaskDetails.getEquipName());
                            meter.setServiceStatus(BusinessConstants.SERVICE_STATUS_IN);
                            mdMeterMapper.insertMdMeter(meter);
                            mdInTaskDetails.setAssetsId(meter.getMeterId());
                        }
                    } else {
                        if (mdInTask.getTaskOrderType().equals(BusinessConstants.TASK_ORDER_TYPE_RETURN)) {
                            meter.setMeterId(mdInTaskDetails.getAssetsId());
                            meter.setCurStatusCode(BusinessConstants.CUR_STATUS_CODE_RETURN);
                            mdMeterMapper.updateMdMeter(meter);
                        }
                    }
                } else if (BusinessConstants.ASSETS_CATEGORY_IT.equals(assetsCategorySelect)) {
                    MdIt mdItTemp = mdItMapper.selectMdItByRfidNo(mdInTaskDetails.getRfidNo());
                    MdIt it = new MdIt();
                    if (StringUtils.isNull(mdItTemp)) {
                        it.setRfidNo(mdInTaskDetails.getRfidNo());
                        it.setCurStatusCode(BusinessConstants.CUR_STATUS_CODE_RETURN);
                        it.setEquipCode(mdInTaskDetails.getEquipCode());
                        it.setEquipName(mdInTaskDetails.getEquipName());
                        it.setServiceStatus(BusinessConstants.SERVICE_STATUS_IN);
                        mdItMapper.insertMdIt(it);
                        mdInTaskDetails.setAssetsId(it.getItId());
                    } else {
                        it.setItId(mdInTaskDetails.getAssetsId());
                        it.setCurStatusCode(BusinessConstants.CUR_STATUS_CODE_RETURN);
                        mdItMapper.updateMdIt(it);
                    }
                } else if (BusinessConstants.ASSETS_CATEGORY_CONCENTRATOR.equals(assetsCategorySelect)) {
                    MdConcentrator mdConcentratorTemp = mdConcentratorMapper.selectMdConcentratorByRfidNo(mdInTaskDetails.getRfidNo());
                    MdConcentrator mdConcentrator = new MdConcentrator();
                    if (StringUtils.isNull(mdConcentratorTemp)) {
                        mdConcentrator.setRfidNo(mdInTaskDetails.getRfidNo());
                        mdConcentrator.setCurStatusCode(BusinessConstants.CUR_STATUS_CODE_RETURN);
                        mdConcentrator.setEquipCode(mdInTaskDetails.getEquipCode());
                        mdConcentrator.setEquipName(mdInTaskDetails.getEquipName());
                        mdConcentrator.setServiceStatus(BusinessConstants.SERVICE_STATUS_IN);
                        mdConcentratorMapper.insertMdConcentrator(mdConcentrator);
                        mdInTaskDetails.setAssetsId(mdConcentrator.getConcentratorId());

                    } else {
                        mdConcentrator.setConcentratorId(mdInTaskDetails.getAssetsId());
                        mdConcentrator.setCurStatusCode(BusinessConstants.CUR_STATUS_CODE_RETURN);
                        mdConcentratorMapper.updateMdConcentrator(mdConcentrator);
                    }
                }
            } else {

                //循环查询
                MdMeter mdMeterTemp = mdMeterMapper.selectMdMeterByRfidNo(mdInTaskDetails.getRfidNo());
                MdIt mdItTemp = mdItMapper.selectMdItByRfidNo(mdInTaskDetails.getRfidNo());
                MdConcentrator mdConcentratorTemp = mdConcentratorMapper.selectMdConcentratorByRfidNo(mdInTaskDetails.getRfidNo());
                if (mdMeterTemp == null && mdItTemp == null && mdConcentratorTemp == null) {
                    System.out.println("未查询到数据，请导入到系统物资信息后再曹组！");
                }
                if (null != mdMeterTemp) {
                    mdMeterTemp.setServiceStatus(BusinessConstants.SERVICE_STATUS_IN);
                    mdMeterMapper.updateMdMeter(mdMeterTemp);
                } else if (null != mdItTemp) {
                    mdItTemp.setServiceStatus(BusinessConstants.SERVICE_STATUS_IN);
                    mdItMapper.updateMdIt(mdItTemp);
                } else if (null != mdConcentratorTemp) {
                    mdConcentratorTemp.setServiceStatus(BusinessConstants.SERVICE_STATUS_IN);
                    mdConcentratorMapper.updateMdConcentrator(mdConcentratorTemp);
                }
            }
            mdInTaskDetailsMapper.insertMdInTaskDetails(mdInTaskDetails);
        }
        return 1;
    }

    /**
     * 修改出入库明细
     *
     * @param mdInTaskMap 出入库明细
     * @return 结果
     */
    @Override
    public int updateMdInTaskDetails(MdInTaskDetailsController.MdInTaskMap mdInTaskMap) throws IOException, ParserConfigurationException, SAXException {
        final String[] IotaskNo = {""};
        transactionTemplate.execute(new TransactionCallback<Void>() {
            @SneakyThrows
            public Void doInTransaction(TransactionStatus status) {
                try {
                    String assetsCategory = mdInTaskMap.getAssetsCategory();
                    List<MdInTaskDetails> mdInTaskDetailsList = mdInTaskMap.getMdInTaskDetailsList();

                    String useEquipment = mdInTaskMap.getUseEquipment();

                    for (MdInTaskDetails mdInTaskDetails : mdInTaskDetailsList) {
                        //修改任务明细
                        MdInTaskDetails mdInTaskDetailsUpdate = new MdInTaskDetails();
                        mdInTaskDetailsUpdate.setInTaskDetailsId(mdInTaskDetails.getInTaskDetailsId());
                        mdInTaskDetailsUpdate.setWhId(mdInTaskDetails.getWhId());
                        mdInTaskDetailsUpdate.setWhAreaId(mdInTaskDetails.getWhAreaId());
                        mdInTaskDetailsUpdate.setStoreAreaId(mdInTaskDetails.getStoreAreaId());
                        mdInTaskDetailsUpdate.setStoreLocId(mdInTaskDetails.getStoreLocId());
                        mdInTaskDetailsUpdate.setIsComplete("1");
                        mdInTaskDetailsUpdate.setOperationDate(DateUtils.getNowDate());
                        mdInTaskDetailsUpdate.setIsNormal("01");
                        mdInTaskDetailsUpdate.setUseEquipment(useEquipment);
                        mdInTaskDetailsMapper.updateMdInTaskDetails(mdInTaskDetailsUpdate);

                        switch (assetsCategory) {
                            case "01":
                                //删除台账
                                MdMeter mdMeter = new MdMeter();
                                mdMeter.setMeterId(mdInTaskDetails.getAssetsId());
                                mdMeter.setWhId(mdInTaskDetails.getWhId());
                                mdMeter.setWhAreaId(mdInTaskDetails.getWhAreaId());
                                mdMeter.setStoreAreaId(mdInTaskDetails.getStoreAreaId());
                                mdMeter.setStoreLocId(mdInTaskDetails.getStoreLocId());
                                mdMeter.setServiceStatus("01");
                                if (StringUtils.isNotNull(mdInTaskDetails.getStatusCode())) {
                                    mdMeter.setCurStatusCode(mdInTaskDetails.getStatusCode());
                                }
                                mdMeterMapper.updateMdMeter(mdMeter);
                                break;
                            case "02":
                                MdIt mdIt = new MdIt();
                                mdIt.setItId(mdInTaskDetails.getAssetsId());
                                mdIt.setWhId(mdInTaskDetails.getWhId());
                                mdIt.setWhAreaId(mdInTaskDetails.getWhAreaId());
                                mdIt.setStoreAreaId(mdInTaskDetails.getStoreAreaId());
                                mdIt.setStoreLocId(mdInTaskDetails.getStoreLocId());
                                mdIt.setServiceStatus("01");
                                if (StringUtils.isNotNull(mdInTaskDetails.getStatusCode())) {
                                    mdIt.setCurStatusCode(mdInTaskDetails.getStatusCode());
                                }
                                mdItMapper.updateMdIt(mdIt);
                                break;
                            case "03":
                                MdLcEquip mdLcEquip = new MdLcEquip();
                                mdLcEquip.setLcEquipId(mdInTaskDetails.getAssetsId());
                                mdLcEquip.setWhId(mdInTaskDetails.getWhId());
                                mdLcEquip.setWhAreaId(mdInTaskDetails.getWhAreaId());
                                mdLcEquip.setStoreAreaId(mdInTaskDetails.getStoreAreaId());
                                mdLcEquip.setStoreLocId(mdInTaskDetails.getStoreLocId());
                                mdLcEquip.setServiceStatus("01");
                                if (StringUtils.isNotNull(mdInTaskDetails.getStatusCode())) {
                                    mdLcEquip.setCurStatusCode(mdInTaskDetails.getStatusCode());
                                }
                                mdLcEquipMapper.updateMdLcEquip(mdLcEquip);
                                break;
                            case "04":
                                MdConcentrator mdConcentrator = new MdConcentrator();
                                mdConcentrator.setConcentratorId(mdInTaskDetails.getAssetsId());
                                mdConcentrator.setWhId(mdInTaskDetails.getWhId());
                                mdConcentrator.setWhAreaId(mdInTaskDetails.getWhAreaId());
                                mdConcentrator.setStoreAreaId(mdInTaskDetails.getStoreAreaId());
                                mdConcentrator.setStoreLocId(mdInTaskDetails.getStoreLocId());
                                mdConcentrator.setServiceStatus("01");
                                if (StringUtils.isNotNull(mdInTaskDetails.getStatusCode())) {
                                    mdConcentrator.setCurStatusCode(mdInTaskDetails.getStatusCode());
                                }
                                mdConcentratorMapper.updateMdConcentrator(mdConcentrator);
                                break;
                            case "05":
                                MdComModule mdComModule = new MdComModule();
                                mdComModule.setModuleId(mdInTaskDetails.getAssetsId());
                                mdComModule.setWhId(mdInTaskDetails.getWhId());
                                mdComModule.setWhAreaId(mdInTaskDetails.getWhAreaId());
                                mdComModule.setStoreAreaId(mdInTaskDetails.getStoreAreaId());
                                mdComModule.setStoreLocId(mdInTaskDetails.getStoreLocId());
                                mdComModule.setServiceStatus("01");
                                if (StringUtils.isNotNull(mdInTaskDetails.getStatusCode())) {
                                    mdComModule.setStatusCode(mdInTaskDetails.getStatusCode());
                                }
                                mdComModuleMapper.updateMdComModule(mdComModule);
                                break;
                            case "10":
                                MdOtherMaterial mdOtherMaterial = new MdOtherMaterial();
                                mdOtherMaterial.setBarCode(mdInTaskDetails.getRfidNo());
                                mdOtherMaterial.setEquipCateg(mdInTaskDetails.getSortCode());
                                mdOtherMaterial.setWhId(mdInTaskDetails.getWhId());
                                mdOtherMaterial.setWhAreaId(mdInTaskDetails.getWhAreaId());
                                mdOtherMaterial.setStoreAreaId(mdInTaskDetails.getStoreAreaId());
                                mdOtherMaterial.setStoreLocId(mdInTaskDetails.getStoreLocId());
                                mdOtherMaterial.setServiceStatus("01");
                                if (StringUtils.isNotNull(mdInTaskDetails.getStatusCode())) {
                                    mdOtherMaterial.setCurStatusCode(mdInTaskDetails.getStatusCode());
                                }
                                mdOtherMaterialMapper.insertMdOtherMaterial(mdOtherMaterial);
                                break;
                        }
                    }

                    //如果任务明细都执行完毕，则更改任务单状态
                    MdInTaskDetails mdInTaskDetailQuery = new MdInTaskDetails();
                    mdInTaskDetailQuery.setIsComplete("0");
                    mdInTaskDetailQuery.setInTaskNo(mdInTaskMap.getInTaskNo());
                    int count = mdInTaskDetailsMapper.selectMdInTaskDetailsCount(mdInTaskDetailQuery);
                    if (count == 0) {
                        MdInTask mdInTask = new MdInTask();
                        mdInTask.setInTaskId(mdInTaskMap.getInTaskId());
                        mdInTask.setStatusCode("2");
                        mdInTask.setOperationDate(DateUtils.getNowDate());
                        mdInTaskMapper.updateMdInTask(mdInTask);

                        if ("2".equals(mdInTaskMap.getTaskOrderType())) {
                            IotaskNo[0] = mdInTaskMap.getInTaskNo();
                        }
                    }

                    // mdInTaskDetailsMapper.updateMdInTaskDetails(mdInTaskDetails);
                } catch (Exception e) {
                    // 发生异常时，回滚事务
                    status.setRollbackOnly();
                    throw e;
                }
                return null;
            }

        });

//        if ("2".equals(mdInTaskMap.getTaskOrderType())) {
//            int i = insetMdIoDetInfo(mdInTaskMap);
//            if (i == 1) {
//                //将出入库设备结果信息插入到中间数据库，同时通知计量服务总线从中间数据库中读取出入库结果信息
//                client.sibSendIOInfo(mdInTaskMap.getOperId().toString());
//                if (!"".equals(IotaskNo[0])) {
//                    client.sibUpIOResult(IotaskNo[0], "2");
//                }
//            }
//        }
        return 1;
    }

    public int insetMdIoDetInfo(MdInTaskDetailsController.MdInTaskMap mdInTaskMap) {
        List<MdInTaskDetails> mdInTaskDetailsList = mdInTaskMap.getMdInTaskDetailsList();
        String assetsCategory = mdInTaskMap.getAssetsCategory();
        for (MdInTaskDetails mdInTaskDetails : mdInTaskDetailsList) {
            //入库设备结果信息插入到中间数据库
//            MdIoDet mdIoDet = new MdIoDet();
//            mdIoDet.setDetId((long) 1);
//            mdIoDet.setIoTaskNo(mdInTaskDetails.getInTaskNo());
//            mdIoDet.setRelaId(mdInTaskMap.getRelaId().toString());
//            //mdIoDet.setStoreLocBar();
//            mdIoDet.setEquipId(mdInTaskDetails.getEquipId());
//            mdIoDet.setBarCode(mdInTaskDetails.getRfidNo());
//            mdIoDet.setMadeNo(mdInTaskDetails.getMadeNo());
//            //设备类别，对应系统  01电能表03互感器09终端
//            mdIoDet.setEquipCateg(assetsCategory);
//            mdIoDet.setWhId(mdInTaskDetails.getWhId());
//            mdIoDet.setWhAreaId(mdInTaskDetails.getWhAreaId());
//            mdIoDet.setStoreAreaId(mdInTaskDetails.getStoreAreaId());
//            mdIoDet.setStoreLocId(mdInTaskDetails.getStoreLocId());
//            mdIoDet.setOperId(mdInTaskMap.getOperId());
//
//            mdIoDetMapper.insertMdIoDet(mdIoDet);
        }
        return 1;
    }

    /**
     * 批量删除出入库明细
     *
     * @param inTaskDetailsIds 需要删除的出入库明细主键
     * @return 结果
     */
    @Override
    public int deleteMdInTaskDetailsByInTaskDetailsIds(Long[] inTaskDetailsIds) {
        return mdInTaskDetailsMapper.deleteMdInTaskDetailsByInTaskDetailsIds(inTaskDetailsIds);
    }

    /**
     * 删除出入库明细信息
     *
     * @param inTaskDetailsId 出入库明细主键
     * @return 结果
     */
    @Override
    public int deleteMdInTaskDetailsByInTaskDetailsId(Long inTaskDetailsId) {
        return mdInTaskDetailsMapper.deleteMdInTaskDetailsByInTaskDetailsId(inTaskDetailsId);
    }

    /**
     * 导入入库明细数据
     *
     * @param inTaskDetailsList 入库明细列表
     * @param inTaskNo          任务编号
     * @return 结果
     */
    @Transactional
    public String importMdInTaskDetails(List<MdInTaskDetails> inTaskDetailsList, String inTaskNo, String assetsCategory, Boolean isCoverSupport) {
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        //如果覆盖先删除
        if (isCoverSupport) {
            mdInTaskDetailsMapper.deleteMdInTaskDetailsByInTaskNo(inTaskNo);
        }
        for (MdInTaskDetails mdInTaskDetails : inTaskDetailsList) {
            //是否操作入库
            boolean isOperation = true;
            //是否继续累计问题数量
            boolean isGoAddProblemNum = true;

            String rfidNo = mdInTaskDetails.getRfidNo();
            try {
                //对象验证
                BeanValidators.validateWithException(validator, mdInTaskDetails);

                switch (assetsCategory) {
                    case "01":
                        MdMeter mdMeter = mdMeterMapper.selectMdMeterByRfidNo(rfidNo);
                        if (StringUtils.isNull(mdMeter)) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、条形码 " + rfidNo + " 的电表信息在台账中不存在");
                            isOperation = false;
                            isGoAddProblemNum = false;
                        } else if (!"00".equals(mdMeter.getServiceStatus())) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、条形码 " + rfidNo + " 的电表不是待入库状态，不能导入明细");
                            isOperation = false;
                            isGoAddProblemNum = false;
                        } else {
                            mdInTaskDetails.setAssetsId(mdMeter.getMeterId());
                        }
                        break;
                    case "02":
                        MdIt mdIt = mdItMapper.selectMdItByRfidNo(rfidNo);
                        if (StringUtils.isNull(mdIt)) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、条形码 " + rfidNo + " 的互感器信息在台账中不存在");
                            isOperation = false;
                            isGoAddProblemNum = false;
                        } else if (!"00".equals(mdIt.getServiceStatus())) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、条形码 " + rfidNo + " 的互感器不是待入库状态，不能导入明细");
                            isOperation = false;
                            isGoAddProblemNum = false;
                        } else {
                            mdInTaskDetails.setAssetsId(mdIt.getItId());
                        }
                        break;
                    case "03":
                        MdLcEquip mdLcEquip = mdLcEquipMapper.selectMdLcEquipByRfidNo(rfidNo);
                        if (StringUtils.isNull(mdLcEquip)) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、条形码 " + rfidNo + " 的终端信息在台账中不存在");
                            isOperation = false;
                            isGoAddProblemNum = false;
                        } else if (!"00".equals(mdLcEquip.getServiceStatus())) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、条形码 " + rfidNo + " 的终端不是待入库状态，不能导入明细");
                            isOperation = false;
                            isGoAddProblemNum = false;
                        } else {
                            mdInTaskDetails.setAssetsId(mdLcEquip.getLcEquipId());
                        }
                        break;
                    case "04":
                        MdConcentrator mdConcentrator = mdConcentratorMapper.selectMdConcentratorByRfidNo(rfidNo);
                        if (StringUtils.isNull(mdConcentrator)) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、条形码 " + rfidNo + " 的集中器信息在台账中不存在");
                            isOperation = false;
                            isGoAddProblemNum = false;
                        } else if (!"00".equals(mdConcentrator.getServiceStatus())) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、条形码 " + rfidNo + " 的集中器不是待入库状态，不能导入明细");
                            isOperation = false;
                            isGoAddProblemNum = false;
                        } else {
                            mdInTaskDetails.setAssetsId(mdConcentrator.getConcentratorId());
                        }
                        break;
                    case "05":
                        MdComModule mdComModule = mdComModuleMapper.selectMdComModuleByRfidNo(rfidNo);
                        if (StringUtils.isNull(mdComModule)) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、条形码 " + rfidNo + " 的通讯模块信息在台账中不存在");
                            isOperation = false;
                            isGoAddProblemNum = false;
                        } else if (!"00".equals(mdComModule.getServiceStatus())) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、条形码 " + rfidNo + " 的通讯模块不是待入库状态，不能导入明细");
                            isOperation = false;
                            isGoAddProblemNum = false;
                        } else {
                            mdInTaskDetails.setAssetsId(mdComModule.getModuleId());
                        }
                        break;
                    case "10":
                        MdOtherMaterial mdOtherMaterial = mdOtherMaterialMapper.selectMdOtherMaterialByBarCode(rfidNo);
                        if (StringUtils.isNull(mdOtherMaterial)) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、条形码 " + rfidNo + " 的其他物资信息在台账中不存在");
                            isOperation = false;
                            isGoAddProblemNum = false;
                        } else if (!"00".equals(mdOtherMaterial.getServiceStatus())) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、条形码 " + rfidNo + " 的其他物资不是待入库状态，不能导入明细");
                            isOperation = false;
                            isGoAddProblemNum = false;
                        } else {
                            mdInTaskDetails.setAssetsId(mdOtherMaterial.getOtherMaterialId());
                        }
                        break;
                }

                MdInTaskDetails mdInTaskDetailsQuery = new MdInTaskDetails();
                mdInTaskDetailsQuery.setRfidNo(mdInTaskDetails.getRfidNo());
                MdInTaskDetails mdInTaskDetailsTemp = mdInTaskDetailsMapper.selectCarryMdInTaskDetailsCount(mdInTaskDetailsQuery);
                if (StringUtils.isNotNull(mdInTaskDetailsTemp)) {
                    if (mdInTaskDetailsTemp.getRepeatNumber() > 0) {
                        if (isGoAddProblemNum) {
                            failureNum++;
                        }
                        failureMsg.append("<br/>" + failureNum + "、条形码 " + rfidNo + " 的信息在" + mdInTaskDetailsTemp.getInTaskNo() + "的任务中已存在");
                        isOperation = false;
                    }
                }

                //执行插入
                if (isOperation) {
                    mdInTaskDetails.setInTaskNo(inTaskNo);
                    mdInTaskDetailsMapper.insertMdInTaskDetails(mdInTaskDetails);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、条形码 " + rfidNo + " 的明细导入成功");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、条形码 " + rfidNo + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
                throw new ServiceException(failureMsg.toString());
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 查询入库数量信息
     *
     * @return 结果
     */
    @Override
    public Map<String, Object> getInNumInfo() {
        Map<String, Object> inNumInfo = new LinkedHashMap<>();

        MdInTaskDetails mdInTaskDetails = new MdInTaskDetails();
        mdInTaskDetails.setIsComplete("1");

        Integer thisWeekInNum = mdInTaskDetailsMapper.getThisWeekInNum(mdInTaskDetails);
        Integer lastWeekInNum = mdInTaskDetailsMapper.getLastWeekInNum(mdInTaskDetails);
        Integer thisMonthInNum = mdInTaskDetailsMapper.getThisMonthInNum(mdInTaskDetails);
        Integer lastMonthInNum = mdInTaskDetailsMapper.getLastMonthInNum(mdInTaskDetails);

        double weekChangeIn = HiultraUtil.countNumChange(thisWeekInNum, lastWeekInNum);
        double monthChangeIn = HiultraUtil.countNumChange(thisMonthInNum, lastMonthInNum);

        inNumInfo.put("本周入库数", thisWeekInNum);
        inNumInfo.put("上周入库数", lastWeekInNum);
        inNumInfo.put("入库周环比变化", weekChangeIn);
        inNumInfo.put("本月入库数", thisMonthInNum);
        inNumInfo.put("上月入库数", lastMonthInNum);
        inNumInfo.put("入库月环比变化", monthChangeIn);
        return inNumInfo;
    }

    //获取设备利用率
    @Override
    public Map<String, Object> getTaskDetailsEquipment() {
        List<MdInTaskDetailsServiceImpl.DataMap> doorList = this.getTaskDetailsData("01");
        List<MdInTaskDetailsServiceImpl.DataMap> handsetList = this.getTaskDetailsData("02");

        Map<String, Object> map = new HashMap<>();
        map.put("doorData", doorList);
        map.put("handsetData", handsetList);
        return map;
    }

    //获取设备利用率
    private List<DataMap> getTaskDetailsData(String useEquipment) {
        List<MdInTaskDetails> mdInTaskDetailsList = mdInTaskDetailsMapper.selectMdInTaskDetailsList(new MdInTaskDetails() {{
            setUseEquipment(useEquipment);
        }});
        List<MdOutTaskDetails> mdOutTaskDetailsList = mdOutTaskDetailsMapper.selectMdOutTaskDetailsList(new MdOutTaskDetails() {{
            setUseEquipment(useEquipment);
        }});
        List<MdChkTaskDetails> mdChkTaskDetailsList = mdChkTaskDetailsMapper.selectMdChkTaskDetailsList(new MdChkTaskDetails() {{
            setUseEquipment(useEquipment);
        }});
        Integer[] taskData = new Integer[3];
        taskData[0] = mdInTaskDetailsList.size();
        taskData[1] = mdOutTaskDetailsList.size();
        taskData[2] = mdChkTaskDetailsList.size();
        List<DataMap> taskList = IntStream.range(0, taskData.length)
                .mapToObj(i -> new DataMap(taskData[i], getTaskName(i)))
                .collect(Collectors.toList());
        return taskList;
    }

    private String getTaskName(int i) {
        if (i == 0) {
            return "入库";
        } else if (i == 1) {
            return "出库";
        } else if (i == 2) {
            return "盘点";
        }
        return "";
    }

    public static class DataMap {
        /**
         * 主键
         */
        private Integer value;

        private String name;

        public DataMap(Integer value, String name) {
            this.value = value;
            this.name = name;
        }

        public Integer getValue() {
            return value;
        }

        public void setValue(Integer value) {
            this.value = value;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
